package com.sangmo.fts.teacher.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.fts.teacher.interfaces.ScoreSettingCollect;
import com.sangmo.fts.teacher.interfaces.ScoreSettingCreation;
import com.sangmo.fts.teacher.model.DurationRatioSetting;
import com.sangmo.fts.teacher.model.GrowthRatioSetting;
import com.sangmo.fts.teacher.model.ScoreSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ScoreSettingService extends DelegateViewService<ScoreSetting> {

    @Autowired
    private ScoreSettingEntityService scoreSettingEntityService;

    @Autowired
    private GrowthSettingEntityService growthSettingEntityService;

    @Autowired
    private DurationRatioSettingEntityService durationRatioSettingEntityService;


    @Override
    protected ViewService<ScoreSetting> getEntityService() {
        return scoreSettingEntityService;
    }

    public ScoreSetting findByUserId() {
        Long createdBy = (Long)UserSession.getUserInterface().getId();
        ScoreSetting scoreSetting = scoreSettingEntityService.findByUserId(createdBy);
        if (null == scoreSetting) {
            ScoreSettingCreation creation = ScoreSettingCreation.defaultOne();
            creation.setUserId(createdBy);
            scoreSetting = this.create(creation);
        }
        return scoreSetting;
    }

    public ScoreSettingCollect findByTeacherId(Long teacherId) {
        ScoreSetting scoreSetting = scoreSettingEntityService.findByUserId(teacherId);
        if (null == scoreSetting) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.scoreSetting.teacher.notExists");
        }
        List<GrowthRatioSetting> growthRatioSettings = growthSettingEntityService.findByScoreSettingId(scoreSetting.getId());
        List<DurationRatioSetting> durationRatioSettings = durationRatioSettingEntityService.findByScoreSettingId(scoreSetting.getId());

        ScoreSettingCollect collect = new ScoreSettingCollect();
        collect.setScoreSetting(scoreSetting);
        collect.setGrowthRatioSettings(growthRatioSettings);
        collect.setDurationRatioSettings(durationRatioSettings);
        return collect;
    }

}
